﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;
using SN.Data;
using System.Data;
using Agro.Library;

namespace Agro.Services {

    public class MenuService : BaseService, IMenuService
    {
        [Ninject.Inject]
        public IRoleService RoleService { get; set; }

        public bool SaveMenu(Models.T_Menu menu, out string msg) {
            msg = string.Empty;
            using (DbTrans trans = DB.BeginTrans()) {
                try {
                    if (menu.Menu_ID > 0) {
                        menu.Attach();
                    }
                    else {
                        menu.Detach();
                    }
                    trans.Save(menu);
                    trans.Update<T_Menu>(T_Menu._.Menu_IsDetail, "1", T_Menu._.Menu_ID == menu.Menu_ParentID);
                    CacheKeys.ClearCacheKeys();//清除菜单缓存
                }
                catch (Exception ex) {
                    trans.Rollback();
                    return false;
                }
                //提交数据
                trans.Commit();
            }
            return true;
        }

        //删除菜单项
        public int DeleteMenu(string id, string pid, int childNum)//返回值1成功，-1不成功
        {
            int returnValue = 0;
            int icount = 0;
            using (DbTrans trans = DB.BeginTrans()) {
                try {

                    //后台验证是否有下级节点
                    icount = trans.Count<T_Menu>(T_Menu._.Menu_ParentID == Convert.ToInt32(id) && new Field("isnull(menu_isdel,'0')") == "0");
                    if (icount > 0) {
                        throw new Exception("不是末级菜单，不允许删除!");
                    }
                    //判断是否在用户功能权限表中使用
                    icount = trans.Count<T_Role_Permission>(T_Role_Permission._.RP_TableID == Convert.ToInt32(id) &&
                                                            T_Role_Permission._.RP_Type == "T_Menu");
                    if (icount > 0) {
                        throw new Exception("该菜单已在功能权限表中占用，不允许操作!");
                    }
                    //T_Menu menu = trans.From<T_Menu>().Where(T_Menu._.Menu_ID == Convert.ToInt32(sarrayLsbh[i])).ToSingle();
                    returnValue = trans.Update<T_Menu>(T_Menu._.Menu_IsDel, "1", T_Menu._.Menu_ID == Convert.ToInt32(id));


                    if (returnValue == 1 && childNum == 1) {
                        trans.Update<T_Menu>(T_Menu._.Menu_IsDetail, "0", T_Menu._.Menu_ID == Convert.ToInt32(pid));
                    }


                }
                catch (Exception ex) {
                    trans.Rollback();
                    return -1;
                }
                //提交数据
                trans.Commit();
                CacheKeys.ClearCacheKeys();//清除菜单缓存
            }
            return 1;
        }

        public DataTable GetMenuDT(string pid) {
            string sql = string.Format("select menu_id,menu_parentid,menu_name,menu_isdetail from t_menu where menu_parentid='{0}' and isnull(menu_isdel,'0')='0' order by menu_order,menu_id", pid);
            DataTable dataTable = DB.FromSql(sql).ToDataTable();
            return dataTable;
        }
        /// <summary>
        /// 首页根据父节点得到子节点和本身节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable TreeGetList(CurrentUser user, string id) {
            DataTable userMenuDT = GetUserMenuIdDT(user);
            DataTable dtResult = userMenuDT.Clone();
            DataRow[] rows = userMenuDT.Select("Menu_ParentID=" + id);
            foreach (DataRow dr in rows) {
                dtResult.ImportRow(dr);
            }
            string url = System.Configuration.ConfigurationSettings.AppSettings["Menu" + id];
            string temp = url;
            WhereClip where = WhereClip.All;

            //只显示report_sfky为1的，即可用的报表
            where = where && T_Report._.Report_Sfky == '1';

            //获取当前用户的所在部门，如果是龙头企业，则应过滤掉只下发给管理部门的报表
            T_Organization organization = GetEntity<T_Organization>(T_Organization._.Organization_ID==user.UserInfo.User_OrganizationID);

           
            if(organization.Organization_Type=="1")
            {
                where = where && T_Report._.Report_Xflx == "1" ;
            }
            
            //如果菜单id为3或4即数据查询和数据分析菜单，则过滤掉五千万那个报表，不在菜单中显示
            switch (id)
            {
                case "3":
                    where = where && T_Report._.Report_Sfmb == 1;
                    break;
                case "4":
                    where = where && T_Report._.Report_Sfmb == 1;
                    break;
            }
            if (!string.IsNullOrEmpty(url)) {

                url = "'" + url + "?reportid='";
                Field[] f = { T_Report._.Report_ID.As("Menu_ID"), T_Report._.Report_Cycle.As("Menu_Cycle"),
                                new Field("report_name +case report_cycle when '01' then ' 【月报】' when '02' then ' 【季报】' else  ' 【年报】' end").As("Menu_NAME"),
                                (new Field(url) + T_Report._.Report_ID).As("Menu_Url"), new Field("'" + id + "'").As("Menu_ParentID"), new Field("'/Content/32/bb.png'").As("Menu_Image") };
                DataTable dt = DB.From<T_Report>().Select(f).Where(where).OrderBy(T_Report._.Report_Xflx.Asc && T_Report._.Report_Cycle.Desc).ToDataTable();

                dtResult = dt.Clone();
                foreach (DataRow dr in dt.Rows) {
                    // DataTable1.Rows.Add(obj);   
                    dtResult.ImportRow(dr);
                }
            }
            return dtResult;
        }

        /// <summary>
        /// 获取用户的菜单权限
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public DataTable GetUserMenuIdDT(CurrentUser user) {
            string key = CacheKeys.GetUserMenuCacheKey(user.UserInfo.User_ID);
            MemoryCacheManager cacheManager = new MemoryCacheManager();
            DataTable dtResult = cacheManager.Get<DataTable>(key);
            if (dtResult == null) {
                dtResult = new DataTable();
                Field[] filed = { T_Menu._.Menu_ID, T_Menu._.Menu_NAME, T_Menu._.Menu_Url, T_Menu._.Menu_ParentID, T_Menu._.Menu_Order, T_Menu._.Menu_Image };
                if (user.UserInfo.IsAdmin()) {
                    dtResult = DB.From<T_Menu>().Where(T_Menu._.Menu_IsShow == 1 && new Field("isnull(menu_isdel,'0')") == "0").Select(filed).OrderBy(T_Menu._.Menu_Order.Asc).ToDataTable();
                }
                else {
                    List<string> userMenuIds = new List<string>();
                    userMenuIds.AddRange(DB.From<T_UserMenu>().Where(T_UserMenu._.UserID == user.UserInfo.User_ID).Select(
                          T_UserMenu._.MenuID).ToListResult<string>());

                    IList<T_Role> userRoleList = RoleService.GetUserRoleList(user.UserInfo.User_ID);
                    if (userRoleList.Count > 0) {
                        userMenuIds.AddRange(DB.From<T_Role_Permission>().Where(T_Role_Permission._.RP_Type == "T_Menu" &&
                         T_Role_Permission._.RP_RoleID.In(userRoleList.Select(m => m.Role_ID).ToArray())).ToList().Select(m => m.RP_TableID).ToArray());
                        userMenuIds = userMenuIds.Distinct().ToList();
                        if (userMenuIds.Count > 0) {
                            dtResult = DB.From<T_Menu>().Where(T_Menu._.Menu_IsShow == 1 && T_Menu._.Menu_ID.In(userMenuIds.ToArray()) && new Field("isnull(menu_isdel,'0')") == "0")
                                .OrderBy(T_Menu._.Menu_Order.Asc).Select(filed).ToDataTable();
                        }
                    }
                }
                cacheManager.Set(key, dtResult, 1);
            }
            return dtResult.Copy();
        }


        public DataTable GetMenuList(SN.Core.QueryBase query, WhereClip wclip) {
            Field[] fields = { T_Menu._.All };
            var section = DB.From<T_Menu>()
                .Where(wclip && new Field("isnull(menu_isdel,'0')") == "0");//添加条件删除标志为0的，即未删除的菜单。
            var dt = section.ToTablePage(query, fields);
            return dt;
        }
    }
}
